<template>
  <div class="tag-manager">
    <!-- 标签管理工具栏 -->
    <div class="tag-toolbar">
      <div class="toolbar-left">
        <el-segmented v-model="activeTab" :options="tabOptions" />
      </div>
      <div class="toolbar-right">
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleCreateTag"
        >
          {{ activeTab === 'file' ? t('favorites.tags.createFileTag') : t('favorites.tags.createNoteTag') }}
        </el-button>
      </div>
    </div>

    <!-- 标签内容区域 -->
    <div class="tag-content">
      <!-- 文件标签管理 -->
      <div v-if="activeTab === 'file'" class="tag-section">
        <div class="tag-stats">
          <el-card shadow="never" class="stats-card">
            <div class="stats-item">
              <div class="stats-number">{{ fileTags.length }}</div>
              <div class="stats-label">{{ t('favorites.tags.totalTags') }}</div>
            </div>
            <div class="stats-item">
              <div class="stats-number">{{ getTotalUsage(fileTags) }}</div>
              <div class="stats-label">{{ t('favorites.tags.totalUsage') }}</div>
            </div>
          </el-card>
        </div>

        <div class="tag-list">
          <div v-if="fileTags.length === 0" class="empty-state">
            <el-empty :description="t('favorites.tags.noFileTags')">
              <el-button type="primary" @click="handleCreateTag">{{ t('favorites.tags.createFirstFileTag') }}</el-button>
            </el-empty>
          </div>
          <div v-else class="tag-grid">
            <el-card
              v-for="tag in fileTags"
              :key="tag.id"
              class="tag-card"
              shadow="hover"
            >
              <div class="tag-header">
                <div class="tag-info">
                  <div
                    class="tag-color"
                    :style="{ backgroundColor: tag.color }"
                  ></div>
                  <div class="tag-name">{{ tag.name }}</div>
                </div>
                <el-dropdown @command="(cmd) => handleTagAction(cmd, tag)">
                  <el-button :icon="More" text />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="edit" :icon="Edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="tag-stats-detail">
                <div class="usage-count">使用次数: {{ tag.usageCount || 0 }}</div>
                <div class="tag-type">文件标签</div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 便签标签管理 -->
      <div v-else class="tag-section">
        <div class="tag-stats">
          <el-card shadow="never" class="stats-card">
            <div class="stats-item">
              <div class="stats-number">{{ noteTags.length }}</div>
              <div class="stats-label">便签标签总数</div>
            </div>
            <div class="stats-item">
              <div class="stats-number">{{ getTotalUsage(noteTags) }}</div>
              <div class="stats-label">总使用次数</div>
            </div>
          </el-card>
        </div>

        <div class="tag-list">
          <div v-if="noteTags.length === 0" class="empty-state">
            <el-empty :description="t('favorites.tags.noNoteTags')">
              <el-button type="primary" @click="handleCreateTag">{{ t('favorites.tags.createFirstNoteTag') }}</el-button>
            </el-empty>
          </div>
          <div v-else class="tag-grid">
            <el-card
              v-for="tag in noteTags"
              :key="tag.id"
              class="tag-card"
              shadow="hover"
            >
              <div class="tag-header">
                <div class="tag-info">
                  <div
                    class="tag-color"
                    :style="{ backgroundColor: tag.color }"
                  ></div>
                  <div class="tag-name">{{ tag.name }}</div>
                </div>
                <el-dropdown @command="(cmd) => handleTagAction(cmd, tag)">
                  <el-button :icon="More" text />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="edit" :icon="Edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete" :icon="Delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="tag-stats-detail">
                <div class="usage-count">使用次数: {{ tag.usageCount || 0 }}</div>
                <div class="tag-type">便签标签</div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑标签弹窗 -->
    <el-dialog 
      v-model="showTagDialog"
      :title="editingTag ? '编辑标签' : '新建标签'"
      width="400px"
    >
      <el-form 
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagFormRules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input 
            v-model="tagForm.name"
            placeholder="请输入标签名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker 
            v-model="tagForm.color"
            :predefine="predefineColors"
          />
        </el-form-item>
        
        <el-form-item label="标签类型" prop="type" v-if="!editingTag">
          <el-radio-group v-model="tagForm.type">
            <el-radio label="file">文件标签</el-radio>
            <el-radio label="note">便签标签</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showTagDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveTag"
          :loading="saving"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { Plus, Edit, Delete, More } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'

// Props
interface Props {
  fileTags: any[]
  noteTags: any[]
}

const props = defineProps<Props>()

// 国际化
const { t } = useI18n()

// Emits
const emit = defineEmits<{
  'create': [tagData: any]
  'update': [tag: any, data: any]
  'delete': [tag: any]
}>()

// 响应式数据
const activeTab = ref('file')
const showTagDialog = ref(false)
const editingTag = ref<any>(null)
const saving = ref(false)
const tagFormRef = ref<FormInstance>()

// 标签页选项
const tabOptions = [
  { label: '文件标签', value: 'file' },
  { label: '便签标签', value: 'note' }
]

const tagForm = reactive({
  name: '',
  color: '#409EFF',
  type: 'file'
})

// 预定义颜色
const predefineColors = [
  '#409EFF',
  '#67C23A',
  '#E6A23C',
  '#F56C6C',
  '#909399',
  '#FF6B6B',
  '#4ECDC4',
  '#45B7D1',
  '#96CEB4',
  '#FFEAA7',
  '#DDA0DD',
  '#98D8C8'
]

// 表单验证规则
const tagFormRules: FormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '标签名称长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择标签类型', trigger: 'change' }
  ]
}

// 计算属性
const getTotalUsage = (tags: any[]) => {
  return tags.reduce((total, tag) => total + (tag.usageCount || 0), 0)
}

// 事件处理
const handleCreateTag = () => {
  editingTag.value = null
  tagForm.name = ''
  tagForm.color = '#409EFF'
  tagForm.type = activeTab.value
  showTagDialog.value = true
}

const handleTagAction = (command: string, tag: any) => {
  switch (command) {
    case 'edit':
      handleEditTag(tag)
      break
    case 'delete':
      handleDeleteTag(tag)
      break
  }
}

const handleEditTag = (tag: any) => {
  editingTag.value = tag
  tagForm.name = tag.name
  tagForm.color = tag.color
  tagForm.type = tag.type
  showTagDialog.value = true
}

const handleDeleteTag = async (tag: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签"${tag.name}"吗？删除后相关的标签关联也会被移除。`,
      '删除标签',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    emit('delete', tag)
  } catch (error) {
    // 用户取消
  }
}

const handleSaveTag = async () => {
  if (!tagFormRef.value) return
  
  try {
    await tagFormRef.value.validate()
    saving.value = true
    
    const tagData = {
      name: tagForm.name,
      color: tagForm.color,
      type: tagForm.type
    }
    
    if (editingTag.value) {
      emit('update', editingTag.value, tagData)
    } else {
      emit('create', tagData)
    }
    
    showTagDialog.value = false
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.tag-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
}

.tag-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
  margin-bottom: 20px;
}

.toolbar-left {
  flex: 1;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.tag-content {
  flex: 1;
  padding: 0 20px 20px;
  overflow-y: auto;
}

.tag-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tag-stats {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
}

.stats-card :deep(.el-card__body) {
  display: flex;
  gap: 40px;
  padding: 20px;
}

.stats-item {
  text-align: center;
}

.stats-number {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.tag-list {
  flex: 1;
  min-height: 300px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.tag-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.tag-card {
  transition: all 0.2s;
}

.tag-card:hover {
  transform: translateY(-2px);
}

.tag-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.tag-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tag-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid var(--el-border-color);
}

.tag-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.tag-stats-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.usage-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.tag-type {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  padding: 2px 8px;
  border-radius: 12px;
}

.tag-dialog .el-form-item {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .tag-grid {
    grid-template-columns: 1fr;
  }
  
  .tag-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .tag-actions {
    align-self: flex-end;
  }
}
</style>
